package br.com.equus.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import br.com.arquitetura.excecao.ExcecaoUtil;
import br.com.arquitetura.service.UniversalManager;
import br.com.equus.entidade.Proprietario;

public class ProprietarioConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		try {
			if (value.isEmpty())
				return null;
			Proprietario p = new Proprietario();
			p.setNome(value);
			try {
				List lista = this.getUniversalManager().listBy(p, false);
				if (lista != null && !lista.isEmpty()) {
					p = (Proprietario) lista.get(0);
				} else {
					p = new Proprietario();
				}
			} catch (Exception e) {
				ExcecaoUtil.tratarExcecao(e);
			}
			return p;

		} catch (Exception e) {
			ExcecaoUtil.tratarExcecao(e);
		}

		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object object) {
		try {

			if (object instanceof String)
				return "";
			Proprietario p = null;
			if (object instanceof Integer) {
				p = (Proprietario) this.getUniversalManager().get(Proprietario.class, (Integer) object);
			} else if (object instanceof Proprietario) {
				if (object == null || ((Proprietario) object).getId() == null) {
					return "";
				}
				p = (Proprietario) this.getUniversalManager().get(Proprietario.class, ((Proprietario) object).getId());
			}

			return p.getNome();
		} catch (Exception e) {
			ExcecaoUtil.tratarExcecao(e);
		}

		return "";
	}

	public UniversalManager getUniversalManager() {
		ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
		WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(context);
		return (UniversalManager) springContext.getBean("universalManager");
	}

}
